<?php


namespace StarCloud\Library\Sdk;

use Framework\DiServices\HttpClient;
use KubAT\PhpSimple\HtmlDomParser;
use Phalcon\Db\Column;
use Phalcon\Di;
use StarCloud\Library\Config;
use StarCloud\Library\Exception;
use StarCloud\Library\HttpCurl;
use StarCloud\Library\Tool;
use StarCloud\Models\Doumvip\KsDayIncome;
use StarCloud\Models\Doumvip\TiktokNew;
use StarCloud\Models\Doumvip\UcDayIncome;

//  curl -H "Host: edith.xiaohongshu.com" -H "Cookie: acw_tc=387a2f726aa18b61f6e0d9e4f6f7a16bd684fd0af805c1db7065d6467f377fa4" -H "x-raw-ptr: 0" -H "x-legacy-fid: 1710138382-0-0-3f9359aad47d28e972a42ed1346ea934" -H "user-agent: discover/8.27 (iPhone; iOS 16.0.3; Scale/3.00) Resolution/1080*1920 Version/8.27 Build/8270555 Device/(Apple Inc.;iPhone10,2) NetType/WiFi" -H "xy-direction: 90" -H "x-xray-traceid: c7190c8b01b9ebdfa2362d491a243348" -H "x-mini-gid: 7d8cf71d94cd55b867820a480b17a5929f28d8b847359204774aec92" -H "x-b3-traceid: 9a052a410e4cb409" -H "x-mini-mua: eyJhIjoiRUNGQUFGMDIiLCJjIjoxMjQ0LCJrIjoiNTY2N2FlZjU1NWIyMTU3NDgzNDczYjRkYjQ0YmFiZjUxODE2NGFlODVhZmFjMjdlYmJlMjczMjVkYTcyMGQwOSIsInAiOiJpIiwicyI6IjZjNGZiNmI4NTUwNDFiOTk5YThhN2Y5YzU1Y2EwYmQwIiwidSI6IjAwMDAwMDAwMWJkM2FkMGZhNWQ2ODM3OWIxMjI4NTViYzU3MTcyM2QiLCJ2IjoiMi4xLjQifQ.2_u7sU6KbfB_yslWqD3Z_VvnS_MdE5RB29wjcBcu9ttmiYPH5tMbAcue59XZYSrQOysn-sQwE8OylWOrrTRNRuE5wXvF9U-FA83LtvbrFVMLite47IiNuxLnht-QPsSy9jxk-5MSkRx7WCJVmZsBMypbOpaea8MFCR3rA5275xglEsrXWsWZwzwcPOBPySjQ-rDq4OKo-ACkr1xkvdvMouBy1QXS2bVicg0TbbuOb5sszDuibgP8vnYqoIVljS2ikGNlh4FLmlLWQjeNXjQWWCwD4xiUPHEuVGGH0y1bXYQI12lQTf_xyikY1lDkhyooN5BhJ1pyMqrCBv8sDJ1lr-7sKHVJgaB0KlVTgJwgzXWGX6feGDwSr84AVntioce-PZ6wT4RpbUl7beHU0iIyuXCth-OW-tHh1c_gJ9lk-A6oaZw6YIsAp-kQCk0QLqkVrSseyM53LosCi6Y5Gx2egRWT0OjwYYq7JxYDzGc41Vj3NCNhgtGXQPNLkpgDqRTvPTAtvbjdGQw7U55-0s0cV9YYW3TlBm9bxdWfHgeWQoV0juFnq2_3fFgLSRGPly6XYozjo4iA1I7YLz4AIeTwinydKe9HMe5CH32wh9PohVE." -H "accept-language: zh-Hans-CN;q=1" -H "x-mini-sig: 37cada185e174d9f432e40d1a98abb6b90665f3388d964f4c608a915217d5458" -H "x-legacy-did: 45A943B3-A68A-49E1-9AED-7C15E2593902" -H "x-net-core: crn" -H "shield: XYAAAAAQAAAAEAAABTAAAAUzUWEe4xG1IYD9/c+qCLOlKGmTtFa+lG434Me+FTQahGwPW5mrUVT52J+eguz8Qjqcx+2NNHZAxJYmSNEbnx1Shphubos8o3ai0J95ahvgKPEMfF" -H "x-legacy-smid: 2024031114262629f30e559ade7b06eb2edb0d3b76ec4c0181af568cd83383" -H "xy-platform-info: platform=iOS&version=8.27&build=8270555&deviceId=45A943B3-A68A-49E1-9AED-7C15E2593902&bundle=com.xingin.discover" -H "content-type: application/json" -H "mode: gslb" -H "x-legacy-sid: session.1710237428034404779655" -H "xy-common-params: app_id=ECFAAF02&build=8270555&channel=AppStore&deviceId=45A943B3-A68A-49E1-9AED-7C15E2593902&device_fingerprint=2024031114262629f30e559ade7b06eb2edb0d3b76ec4c0181af568cd83383&device_fingerprint1=2024031114262629f30e559ade7b06eb2edb0d3b76ec4c0181af568cd83383&device_model=phone&fid=1710138382-0-0-3f9359aad47d28e972a42ed1346ea934&gid=7d8cf71d94cd55b867820a480b17a5929f28d8b847359204774aec92&identifier_flag=1&is_mac=0&lang=zh-Hans&launch_id=731921913&platform=iOS&project_id=ECFAAF&sid=session.1710237428034404779655&t=1710237488&teenager=0&tz=Asia/Shanghai&uis=light&version=8.27" -H "accept: */*" -H "referer: https://app.xhs.cn/" --data-binary "{\"source\":6,\"userIds\":[\"5b6f1d0ce6eee40001dac832\",\"6017e12c000000000100219f\",\"6389c747000000001f015199\",\"6473c6a1000000002b00a402\",\"5bdd6403d5989900011187ab\"]}" --compressed "https://edith.xiaohongshu.com/api/im/private/query_online_status"
class HongshuBot
{
    use HttpCurl;

    /* @var $httpClient HttpClient */
    private $httpClient = null;

    protected $taskId = 125650;
    protected $bountyId = '60013';

    const BOUNTYID_NOVEL = '60013';
    const BOUNTYID_SOURCE = '90010';

    public function __construct($bountyId = '')
    {
        if (!empty($bountyId)) {
            $this->bountyId = $bountyId;
        }
        $this->httpClient = Di::getDefault()->get('httpClient');
        $this->cacheClass = Di::getDefault()->get('redis');
    }

    public function getTaskDetail($taskId, $url = '')
    {
        if(!$this->login()) {
            throw new Exception(9999, "鉴权失败");
        }
        $body = [
        ];

        $response = $this->httpClient->sendGetRequest('https://edith.xiaohongshu.com/api/growth/fantasy/apply/detail?applyId='.$taskId, $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);
        if (isset($json['code']) && $json['code'] == 0) {
            $result = $json['data']['response'];

            foreach ($result['nodes'] as $node) {
                if ($node['title'] == '选择计费周期' && $node['status'] == 'ONGOING') {
                    $this->selectSettleTime($taskId);
                }

                if (!empty($url) && $node['title'] == '回填链接' && $node['status'] == 'ONGOING') {
                    var_dump("insertPlatform");
                     $this->insertPlatform($taskId, $url);
                }
            }
            return $result;
        } else {
           return '';
        }
    }

    public function getUserNum($taskId)
    {
         $body = [
         ];
        $response = $this->httpClient->sendGetRequest('https://edith.xiaohongshu.com/api/growth/fantasy/record/get_stat?applyRecordId='.$taskId, $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);
        var_dump($taskId, $json);
        return $json['data']['virtualAcquisition'] ?? 0;
    }

    public function selectSettleTime($taskId)
    {
        $body = [
            'applyId' => $taskId,
            'dateTime' => date('Y-m-d')
        ];

        $response = $this->httpClient->sendPostRequest('https://edith.xiaohongshu.com/api/growth/fantasy/apply/bill_start_time', $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);
        if (isset($json['code']) && $json['code'] == 0) {
            return $json;
        } else {
            return false;
        }
    }

    public function login($isDebug = false)
    {
        $token = $this->getCacheAnthorization();
        if ($token && !$isDebug) {
            $this->getTaskStatus(158018, true);
            return $token;
        }
        $url = 'https://edith.xiaohongshu.com/api/growth/fantasy/user/login';
        $body = [
            "code" => $this->getCode(),
        ];

        $response = $this->httpClient->sendPostRequest($url, $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['data']['authorization'])) {
            $this->setCacheAnthorization($json['data']['authorization']);
            return $json['data']['authorization'];
        } else {
            return false;
        }
    }

    public function setCacheAnthorization($authorization){
        $key = 'hongshu_authorization2024';
        $this->cacheClass->set($key, $authorization, 12 * 3600);
    }

    public function getCacheAnthorization()
    {
        $key = 'hongshu_authorization2024';
        return  $this->getCache($key);
    }

    public function getCode()
    {
        $url = 'https://www.xiaohongshu.com/api/sns/v1/mp/red/login?sid=session.1719851740872792674266';

        $body = [
            "appid" => "65672f854fe8d0004a7c32a7",
        ];

        $response = $this->httpClient->sendPostRequest($url, $body, $this->getLoginHeader());

        $json = json_decode($response->getBody()->getContents(), true);
        if (isset($json['data']['code'])) {
            return $json['data']['code'];
        } else {
            throw new Exception(9999, $json['msg']);
        }
    }

    public function getLoginHeader()
    {
        return [
            'Cookie' => 'acw_tc=181065de5e03b6881e7296664ab492a7e3b8d99a28cbef77cad91c425039d232;feredcity-status=online;feredcity-status.sig=lKqySa4AOibaymDO2ElaBZiqq9S1Nyi4OnVDdDJeEyU',
            'content-type' => 'application/json',
            'x-legacy-did' => '45A943B3-A68A-49E1-9AED-7C15E2593902',
            "x-mini-mua" => 'eyJhIjoiRUNGQUFGMDIiLCJjIjoyNDMsImsiOiI2MzI2NWFjYTU5NTA5OGFhMjg0ODQ4MDM0NmViOWQ5ZmY0NDdkYjRiMWQ0YzdjMGU3NTA3NTk1NmY4ZDc3NTcwIiwicCI6ImkiLCJzIjoiMzM3NjQ3MTc1ZjgzMjBiOTk2ZGVlMDc5MjcyMDE5YTciLCJ1IjoiMDAwMDAwMDAxYmQzYWQwZmE1ZDY4Mzc5YjEyMjg1NWJjNTcxNzIzZCIsInYiOiIyLjEuNCJ9.0xWVBmfbdL4MKBiPoTRa-mQLrvWMvrsoS0gwpD6yDX-eAwj8op4j4PpPAjjjJNrk6qDp7vLuUflpXHe7hG8OHwRYsJPxEAYm0yhe0h0x3Kejnw9tTOUjm2JD-lBTjqUKCodOwfuQQG-opSzZMdFCfnw_k5RMKq8cYtu9l3_FHbFsN7TxG5M6HOm-qMejq4-yFFOxVFyikaIKWJhGP7aummVzINeqq5EvmocNpl3GPBX8F0F1Y85pwSzKoNWG-BifSGqhNKq3iMJK763mOI5mhu_BKRD4yI3kiL85tPVxi5LndsGSOBlHP3GgzaKtJxPSGtuDy4488ZjV6rbWKu-l9q6MbFfUhOvvkTv6Kx6V9Fej7WvE2h1iLcxwgfj9uCceGvhLVhRnJZqxmfl4l6lBfHL0y4wPp8rvaqJzoGVcDKNnnDDTbx38fgJx3uDnlv0aWP1Cy4Mlsm_w8MIWVVNyN4duOHkUUqR13CdExX7OU49xM9c1GEpOuO64m7Wc7n404t2tO3Dysi2oZvoSpQhtooPWxxCLVYA9XZT81CbYXUqvKvlD3YcDsf8vm0iNtpNHBVRepnIsGsX-Ra3q8yjUq-LLAcAo7-Hofmz0FQwh0tn-nUak4C1suT9_P-ChIoqC.'
        ];
    }

    public function getHeader()
    {
        return [
            'Cookie' => 'cw_tc=387a2f726aa18b61f6e0d9e4f6f7a16bd684fd0af805c1db7065d6467f377fa4',
            'content-type' => 'application/json',
            'x-net-core' => 'crn',
            'authorization' => $this->getCacheAnthorization(),
            'x-legacy-did' => '45A943B3-A68A-49E1-9AED-7C15E2593902',
            'x-legacy-sid' => 'session.1710237428034404779655',
        ];
    }

    public function insertPlatform($taskId, $link)
    {
        if(!$this->login()) {
            throw new Exception(9999, "鉴权失败");
        }
        $url = 'https://edith.xiaohongshu.com/api/growth/fantasy/record/insert_platform_info';

        $body = [
            'links' => [$link],
            "id" => $taskId,
            'platform' => '抖音'
        ];

        $response = $this->httpClient->sendPostRequest($url, $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['code']) && $json['code'] == 0) {
            return $json;
        } else {
            throw new Exception(9999, $json['msg']);
        }
    }

    public function checkKeyword($keyword, $taskId)
    {
        if(!$this->login()) {
            throw new Exception(9999, "鉴权失败");
        }
        $body = [
            'keyword' => $keyword,
            "id" => $taskId
        ];

        $response = $this->httpClient->sendPostRequest('https://edith.xiaohongshu.com/api/growth/fantasy/keyword/check', $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);
        if (isset($json['code']) && $json['code'] == 0) {
            return $json;
        } else {
            throw new Exception(9999, $json['msg']);
        }
    }

    public function getTaskStatus($taskId, $isDebug = false)
    {
        if (!$isDebug) {
            if(!$this->login()) {
                throw new Exception(9999, "鉴权失败");
            }
        }

        $url = 'https://edith.xiaohongshu.com/api/growth/fantasy/record/get?id='.$taskId;

        $response = $this->httpClient->sendGetRequest($url, [], $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);
        if (isset($json['code']) && $json['code'] == 0) {
            return [$json['data']['response']['stage'], $json['data']['response']['content']['denyReason'] ?? ''];
        } elseif (isset($json['code']) && $json['code'] == 1000) {
            return $this->login(true);
        }else {
            throw new Exception(9999, $json['msg']);
        }
    }

    public function join()
    {
        if(!$this->login()) {
            throw new Exception(9999, "鉴权失败");
        }
        $body = [
            "bountyId" => $this->bountyId,
        ];

        $response = $this->httpClient->sendPostRequest('https://edith.xiaohongshu.com/api/growth/fantasy/bounty/join', $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);
        if (isset($json['code']) && $json['code'] == 0) {
            return $json['data']['response']['id'];
        } else {
            throw new Exception(9999, $json['msg']);
        }
    }

    public function closeTask($taskId)
    {
        $url = 'https://edith.xiaohongshu.com/api/growth/fantasy/record/update';

        $body = [
            "request" => [
                "id" => $taskId,
		        "stage" => "CLOSE"
            ],
        ];

        $response = $this->httpClient->sendPostRequest($url, $body, $this->getHeader());
        $json = json_decode($response->getBody()->getContents(), true);
        var_dump($json);
        if (isset($json['code']) && $json['code'] == 0) {
            return true;
        } else {
            return false;
        }
    }

    public function createKeyword($keyword, $link = '', $sucai = '')
    {
        if(!$this->login()) {
            throw new Exception(9999, "鉴权失败");
        }

        $this->checkKeyword($keyword, $this->taskId);
        $taskId = $this->join();
        $body =
            array(
                'request' =>
                    array(
                        'id' => $taskId,
                        'stage' => 'AUDITING',
                        'content' =>
                            array(
                                'materialList' =>
                                    array(
                                        0 =>
                                            array(
                                                'fileId' => 'kratosjr/vPd9tCzxTFJ-gRBlNMKqW48e-vzZfAZfvSJwykSb93poVw4',
                                                'materialType' => 'KOC_PIC',
                                                'width' => 543,
                                                'height' => 540,
                                            ),
                                    ),
                                'attributions' =>
                                    array(
                                        0 =>
                                            array(
                                                'keyword' => $keyword,
                                                'topLink' => $link,
                                            ),
                                    ),
                                'title' => $keyword,
                                'platformContent' =>
                                    array(
                                        '抖音' => '',
                                    ),
                                'text' => '推荐来看',
                            ),
                    ),
            );
//        if (!empty($sucai)) {
//            $body['request']['content']['materialList'] = [json_decode($sucai, true)];
//        }

        $response = $this->httpClient->sendPostRequest('https://edith.xiaohongshu.com/api/growth/fantasy/record/update', $body, $this->getHeader());

        $json = json_decode($response->getBody()->getContents(), true);

        if (isset($json['code']) && $json['code'] == 0) {
            return $taskId;
        } else {
            throw new Exception(9999, $json['msg']);
        }
    }
}

